package com.ruoyi.booking.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.booking.domain.DbUsers;
import com.ruoyi.booking.service.IDbUsersService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.AesCbcUtil;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sign.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信操作Controller
 * 
 * @author ruoyi
 * @date 2021-12-03
 */
@RestController
@RequestMapping("/app/wechat")
public class WechatController extends BaseController
{
    @Autowired
    private IDbUsersService dbUsersService;

    @PostMapping("/login")
    public @ResponseBody AjaxResult login(@RequestBody Map data) {
        String code = (String) data.get("code");

        String response = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session", "appid=wx226448bc5b7924d3"
                + "&secret=c68cbb82db28434c8b2750b2ca0d47d8" + "&js_code=" + code
                + "&grant_type=authorizatiion_code");

        JSONObject obj = (JSONObject) JSON.parse(response);

        String session_key = obj.getString("session_key");
        String openid = obj.getString("openid");

        Map resultMap = new HashMap();
        resultMap.put("session_key", session_key);
        resultMap.put("openid", openid);

        return AjaxResult.success("登录成功", resultMap);
    }

    // decryptPhone

    @PostMapping("/decryptPhone")
    public @ResponseBody AjaxResult decryptPhone(@RequestBody Map data) {
        String encryptedData = (String) data.get("encryptedData");
        String iv = (String) data.get("iv");
        String sessionKey = (String) data.get("sessionKey");
        String openid = (String) data.get("openid");
        Map resultMap = new HashMap();
        int flag = 0;
        try {
            String result = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
            resultMap = JSON.parseObject(result);
            String phoneNumber = (String) resultMap.get("phoneNumber");

            DbUsers dbUsers = new DbUsers();
            dbUsers.setOpenid(openid);
            dbUsers.setMobile(phoneNumber);
            flag = dbUsersService.saveOrUpdateUser(dbUsers);

            System.out.println(flag);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.success("绑定成功", resultMap);
    }

    /**
     * 查询菜单记录列表
     */
    @GetMapping("/deciphering")
    public @ResponseBody
    String deciphering(String encrypdata,
                       String ivdata, String sessionkey,
                       HttpServletRequest request) {

        byte[] encrypData = Base64.decode(encrypdata);
        byte[] ivData = Base64.decode(ivdata);
        byte[] sessionKey = Base64.decode(sessionkey);
        String str="";
        try {
            str = decrypt(sessionKey,ivData,encrypData);
        } catch (Exception e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(str);
        return str;

    }

    public static void main(String[] args) {
        byte[] encrypData = Base64.decode("g8VY8yoHCOiuvgWaEZ9C9s/P7z7BJpR2imdifHRXRWo4AIXxXO7TxXUXitEwSBs22za3v2dV/thqEbIdV0ALrQYTUImkv+SvPMnX1UAmvmG6+K4Q+70/qqS2NJ9e/FmpFl82ngD7NwNaCPSbXXbXPHnTrIuqMAY1SEYyPrYGui4yOJTKA1RUEud815t4QHBR6KtF4HybPIYVdGjs7pw/SQ==");
        byte[] ivData = Base64.decode("ej6Qnl2u+4dNGBY/mKSB6A==");
        byte[] sessionKey = Base64.decode("51_prmkgxksUiVplXGVJLfN8Hbr6TQYimTgUwUPpgUXQ3gYT2OhUbFDHQpyf7U");
        String str="";
        try {
            str = decrypt(sessionKey,ivData,encrypData);
        } catch (Exception e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(str);
    }

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串
        return new String(cipher.doFinal(encData),"UTF-8");
    }
}
